<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>注册表单</title>
		<script src="../js/crypto-js.js"></script>
		<link href="../css/register.css" rel="stylesheet" />
		<script src="../js/mui.min.js"></script>
		<link href="../css/mui.min.css" rel="stylesheet" />
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class=" mui-icon mui-icon-left-nav" href="./login.html"></a>
		</header>
		<div class="form-container">
			<h2>注册</h2>
			<form id="register-form">
				<div class="form-group">
					<label for="username">用户名</label>
					<input type="text" id="username" name="username" placeholder="请输入用户名">
					<div id="username-error" class="error"></div>
				</div>
				<div class="form-group">
					<label for="password">密码</label>
					<input type="password" id="password" name="password" placeholder="请输入密码">
					<div id="password-error" class="error"></div>
				</div>
				<div class="form-group">
					<label for="email">邮箱</label>
					<input type="email" id="email" name="email" placeholder="请输入邮箱">
					<div id="email-error" class="error"></div>
				</div>
				<label for="email-captcha">邮箱验证码</label>
				<div class="form-group captcha-container">
					<input type="text" id="email-captcha" name="email-captcha" placeholder="请输入验证码">
					<button type="button" id="email-captcha-btn" class="captcha-btn">获取验证码</button>
					<div id="email-captcha-error" class="error"></div>
				</div>
				<div class="form-group">
					<button type="submit">注册</button>
				</div>
			</form>
			<div>
				<p>点击注册即表示您同意 <a href="javascript:void(0);" id="user-agreement">用户协议</a> 和 <a href="javascript:void(0);"
						id="privacy-policy">隐私政策</a></p>
			</div>
		</div>

		<!-- 用户协议模态框 -->
		<div id="user-agreement-modal" class="modal">
			<div class="modal-content">
				<h3>用户协议</h3>
				<p>这里是用户协议的内容...</p>
				<button id="close-user-agreement" class="close-btn">关闭</button>
			</div>
		</div>

		<!-- 隐私政策模态框 -->
		<div id="privacy-policy-modal" class="modal">
			<div class="modal-content">
				<h3>隐私政策</h3>
				<p>这里是隐私政策的内容...</p>
				<button id="close-privacy-policy" class="close-btn">关闭</button>
			</div>
		</div>


		<script>
			function generateSalt(length = 16) {
				const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				let salt = '';
				for (let i = 0; i < length; i++) {
					const randomIndex = Math.floor(Math.random() * charset.length);
					salt += charset[randomIndex];
				}
				return salt;
			}

			function hashPasswordWithSalt(password) {
				// 生成一个随机盐值
				const salt = generateSalt(16);

				// 将盐值和密码结合
				const passwordWithSalt = password ;

				// 使用 SHA-256 进行哈希
				//const hashedPassword = CryptoJS.SHA256(passwordWithSalt);

				// 返回盐值和哈希后的密码
				return {
					salt,
					password
				};
			}
			// 验证表单
			function validateForm() {
				let valid = true;

				// 获取表单字段值
				const username = document.getElementById('username').value;
				const password = document.getElementById('password').value;
				const email = document.getElementById('email').value;
				const emailCaptcha = document.getElementById('email-captcha').value;

				// 清除之前的错误提示
				document.getElementById('username-error').textContent = '';
				document.getElementById('password-error').textContent = '';
				document.getElementById('email-error').textContent = '';
				document.getElementById('email-captcha-error').textContent = '';

				// 用户名验证
				if (username === '') {
					document.getElementById('username-error').textContent = '用户名不能为空';
					valid = false;
				}

				// 密码验证
				if (password === '') {
					document.getElementById('password-error').textContent = '密码不能为空';
					valid = false;
				}

				// 邮箱验证
				const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
				if (email === '') {
					document.getElementById('email-error').textContent = '邮箱不能为空';
					valid = false;
				} else if (!emailRegex.test(email)) {
					document.getElementById('email-error').textContent = '请输入有效的邮箱地址';
					valid = false;
				}

				// 验证邮箱验证码
				if (emailCaptcha === '') {
					document.getElementById('email-captcha-error').textContent = '请输入验证码';
					valid = false;
				}

				return valid;
			}

			// 提交表单时进行验证
			document.getElementById('register-form').addEventListener('submit', function(event) {
				event.preventDefault(); // 阻止表单默认提交

				if (validateForm()) {
					//加密密码
					//const {
					//	salt,
					//	passwords
					//} = hashPasswordWithSalt(password);
					const salt = generateSalt(16);
					const username = document.getElementById('username').value;
					const email = document.getElementById('email').value;
					const password = document.getElementById('password').value;
					// 表单通过验证，进行提交操作
					fetch('http://tcp.gykang.eu.org:8080/api/register', {
							method: 'POST',
							headers: {
								'Content-Type': 'application/json'
							},
							body: JSON.stringify({
								username: username,
								password: password,
								mail: email,
								salt: salt
							})
						})
						.then(response => {
							if (!response.ok) { // 如果响应状态码不是 2xx，抛出异常
								throw new Error(`HTTP 错误! 状态码: ${response.status}`);
							}
							return response.json();
						})
						.then(data => {
							if (data.code == 200) {
								mui.toast('注册成功！');
								document.getElementById('username').value = '';
								document.getElementById('password').value = '';
								document.getElementById('email').value = '';
								document.getElementById('email-captcha').value = '';
							} else {
								mui.toast(data.msg); // 处理服务器返回的消息
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
						});

				}
			})


			// 获取验证码的按钮逻辑（这里只是模拟一下）
			document.getElementById('email-captcha-btn').addEventListener('click', function() {
				mui.toast('验证码已发送至您的邮箱');
			});

			// 获取模态框元素
			const userAgreementModal = document.getElementById("user-agreement-modal");
			const privacyPolicyModal = document.getElementById("privacy-policy-modal");

			// 获取关闭按钮
			const closeUserAgreementBtn = document.getElementById("close-user-agreement");
			const closePrivacyPolicyBtn = document.getElementById("close-privacy-policy");

			// 打开用户协议模态框
			document.getElementById("user-agreement").addEventListener("click", function() {
				userAgreementModal.style.display = "flex";
			});

			// 打开隐私政策模态框
			document.getElementById("privacy-policy").addEventListener("click", function() {
				privacyPolicyModal.style.display = "flex";
			});

			// 点击关闭按钮关闭模态框
			closeUserAgreementBtn.addEventListener("click", function() {
				userAgreementModal.style.display = "none";
			});

			closePrivacyPolicyBtn.addEventListener("click", function() {
				privacyPolicyModal.style.display = "none";
			});

			// 点击模态框外部区域时关闭模态框
			userAgreementModal.addEventListener("click", function(event) {
				if (event.target === userAgreementModal) {
					userAgreementModal.style.display = "none";
				}
			});

			privacyPolicyModal.addEventListener("click", function(event) {
				if (event.target === privacyPolicyModal) {
					privacyPolicyModal.style.display = "none";
				}
			});
		</script>
	</body>
</html>